package com.skivingcloud.admin.utils;

import java.util.*;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.skivingcloud.admin.sys.entity.User;



public class PasswordHelper {
	private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private static String algorithmName = "md5";
	private static int hashIterations = 2;

	public static User encryptPassword(User user) {
		String salt = "";
		if(user.getSalt() != null && !user.getSalt().equals("")){
			salt = user.getSalt();
		}else{
			salt = randomNumberGenerator.nextBytes().toHex();
		}
		user.setSalt(salt);
		String newPassword = new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getUsername()+salt), hashIterations).toHex();
		user.setPassword(newPassword);
		return user;
	}
	
	/**
     * 随机生成密码
     * @param length 密码的长度
     * @return 最终生成的密码
     */
	public static String generatePassword (int length) {
        // 最终生成的密码
        String password = "";
        Random random = new Random();
        for (int i = 0; i < length; i ++) {
            // 随机生成0或1，用来确定是当前使用数字还是字母 (0则输出数字，1则输出字母)
            int charOrNum = random.nextInt(2);
            if (charOrNum == 1) {
                // 随机生成0或1，用来判断是大写字母还是小写字母 (0则输出小写字母，1则输出大写字母)
                int temp = random.nextInt(2) == 1 ? 65 : 97;
                password += (char) (random.nextInt(26) + temp);
            } else {
                // 生成随机数字
                password += random.nextInt(10);
            }
        }
        return password;
    }


	public static void main(String[] args) {
		// PasswordHelper passwordHelper = new PasswordHelper();
		try {
			// List<TreeUtils> a = passwordHelper.getStationList();
			// System.out.println(a.toArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		/*User user = new User();
		//user.setDescription("管理员");
		user.setUsername("admin");
		user.setPassword("111111");
		user.setSalt("4157c3feef4a6ed91b2c28cf4392f2d1");
		user = passwordHelper.encryptPassword(user);
		System.out.println("==password=="+user.getPassword()+"==========="+user.getUsername());*/
//		System.out.println(generatePassword(10));
	}
}
